"""
联系人相关的Pydantic模式定义
"""

from pydantic import BaseModel, validator, EmailStr
from typing import Optional, List, Dict, Any
from datetime import datetime


class ContactBase(BaseModel):
    """联系人基础模式"""
    name: str
    email: EmailStr
    phone: Optional[str] = None
    company: Optional[str] = None
    department: Optional[str] = None
    position: Optional[str] = None
    
    @validator('name')
    def validate_name(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('姓名不能为空')
        return v.strip()
    
    @validator('phone')
    def validate_phone(cls, v):
        if v and len(v.strip()) == 0:
            return None
        return v.strip() if v else None


class ContactCreate(ContactBase):
    """创建联系人请求模式"""
    pass


class ContactUpdate(BaseModel):
    """更新联系人请求模式"""
    name: Optional[str] = None
    email: Optional[EmailStr] = None
    phone: Optional[str] = None
    company: Optional[str] = None
    department: Optional[str] = None
    position: Optional[str] = None
    
    @validator('name')
    def validate_name(cls, v):
        if v is not None and (not v or len(v.strip()) < 1):
            raise ValueError('姓名不能为空')
        return v.strip() if v else v


class ContactResponse(ContactBase):
    """联系人响应模式"""
    id: int
    user_id: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class ContactList(BaseModel):
    """联系人列表响应模式"""
    items: List[ContactResponse]
    total: int
    page: int
    size: int
    pages: int


class ContactQuery(BaseModel):
    """联系人查询请求模式"""
    data_source_id: int
    search: Optional[str] = None
    filters: Optional[Dict[str, Any]] = None
    page: int = 1
    size: int = 10
    
    @validator('page')
    def validate_page(cls, v):
        if v < 1:
            raise ValueError('页码必须大于0')
        return v
    
    @validator('size')
    def validate_size(cls, v):
        if not 1 <= v <= 100:
            raise ValueError('每页数量必须在1-100之间')
        return v


class ContactQueryResponse(BaseModel):
    """联系人查询响应模式"""
    contacts: List[Dict[str, Any]]
    total: int
    page: int
    size: int
    pages: int
    columns: List[str]
    data_source_name: str
    data_source_type: str


class ContactImportRequest(BaseModel):
    """联系人导入请求模式"""
    data_source_id: int
    column_mapping: Dict[str, str]  # 数据源列名 -> 联系人字段名的映射
    import_all: bool = False
    selected_rows: Optional[List[int]] = None
    
    @validator('column_mapping')
    def validate_column_mapping(cls, v):
        required_fields = ['name', 'email']
        for field in required_fields:
            if field not in v.values():
                raise ValueError(f'必须映射{field}字段')
        return v


class ContactImportResponse(BaseModel):
    """联系人导入响应模式"""
    success_count: int
    error_count: int
    total_count: int
    errors: List[Dict[str, Any]]
    message: str


class ContactExportRequest(BaseModel):
    """联系人导出请求模式"""
    format: str = "csv"  # csv, excel
    filters: Optional[Dict[str, Any]] = None
    columns: Optional[List[str]] = None
    
    @validator('format')
    def validate_format(cls, v):
        if v not in ['csv', 'excel']:
            raise ValueError('导出格式只支持csv或excel')
        return v


class ContactStatistics(BaseModel):
    """联系人统计信息"""
    total: int
    by_company: Dict[str, int]
    by_department: Dict[str, int]
    recent_added: int  # 最近7天新增
    
    
class ContactFieldMapping(BaseModel):
    """联系人字段映射"""
    source_column: str
    target_field: str
    field_type: str
    is_required: bool
    sample_value: Optional[str] = None


class ContactPreviewRequest(BaseModel):
    """联系人预览请求模式"""
    data_source_id: int
    column_mapping: Dict[str, str]
    limit: int = 10
    
    @validator('limit')
    def validate_limit(cls, v):
        if not 1 <= v <= 50:
            raise ValueError('预览行数必须在1-50之间')
        return v


class ContactPreviewResponse(BaseModel):
    """联系人预览响应模式"""
    preview_data: List[Dict[str, Any]]
    total_rows: int
    valid_count: int
    invalid_count: int
    validation_errors: List[Dict[str, Any]]
